package webserver;

import java.io.IOException;
import java.net.Socket;
import java.net.URISyntaxException;
import java.util.Map;

public class Service implements Runnable, Logger {
	private Server server;
	private Socket socket;
	private int serviceID;

	public Service(Server server, Socket socket, int serviceID) {
		Control.getInstance().log(this, "Got socket " + socket);

		this.server = server;
		this.socket = socket;
		this.serviceID = serviceID;
	}

	public void closeSocket() {
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		server.removeService(serviceID);
	}

	@Override
	public void run() {
		try {
			Request req;
			try {
				req = new Request(
						new SocketInputStream(socket.getInputStream()));
				Servlet servlet = new Servlet(server.documentRoot);
				Response response = servlet.service(req);

				// write response...
				socket.getOutputStream().write(response.getBytes());

				Control.getInstance().log(this, "** REQUEST **\n");
				Control.getInstance().log(this, req.getMethod() + " " + req.getRequestURI() + "\n");
				for (Map.Entry<String, String> entry : req.entrySet()) {
					Control.getInstance().log(this, entry.getKey() + ": " + entry.getValue());
				}
				Control.getInstance().log(this, "\n** RESPONSE **\n");
				Control.getInstance().log(this, new String(response.getHeader()));
			} catch (URISyntaxException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			Control.getInstance().log(this, "IOException: " + e.getMessage());
		} finally {
			closeSocket();
		}
	}

	@Override
	public int getID() {
		return serviceID;
	}

}
